package com.qf.java2105.huangchuang.hotel.controller.food;

import com.qf.java2105.huangchuang.hotel.entity.ResultVO;
import com.qf.java2105.huangchuang.hotel.factory.BeanFactory;
import com.qf.java2105.huangchuang.hotel.pojo.Food;
import com.qf.java2105.huangchuang.hotel.service.IFoodService;
import com.qf.java2105.huangchuang.hotel.service.impl.FoodServiceImpl;
import com.qf.java2105.huangchuang.hotel.utils.MyStringUtils;
import com.qf.java2105.huangchuang.hotel.utils.UploadFileUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 菜品添加控制
 * @author hcvg
 * @version v1.0
 * @date 2021/09/12
 **/
@WebServlet("/food/save")
@MultipartConfig
public class FoodSaveController extends HttpServlet {
    IFoodService foodService  = (IFoodService) BeanFactory.getBean("foodService");
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ResultVO<String> resultVO = null;
        try {
            // 上传文件
            String foodImagesPath = UploadFileUtils.uploadFile(request, "imageUrl", request.getContextPath() + "/images/food/");

            // 获取前台数据
            Map<String, String[]> parameterMap = request.getParameterMap();
            Food food = new Food();
            // BeanUtils封装
            BeanUtils.populate(food, parameterMap);
            // 将上传的图片对应到菜品中
            food.setFoodImage(foodImagesPath);

            resultVO = foodService.save(food);
            if (resultVO.getSuccess()){
                // 更新菜品成功跳转到菜品列表页,本质上是去查询所有菜品
                response.sendRedirect(request.getContextPath() + "/food/search");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.getWriter().write("<script>alert(" + resultVO.getMessage() + ");</script>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
